
import _this from "@/main.js";

/**
 * @description: 保存数据到本地缓存
 * @param {string} key       保存到key值，如果是一个对象，将直接把对象保存到本地
 * @param {string} val       保存的value值
 * @param {string} partition 保存到哪个存储区域，非必填，默认是seemall
 * @return: {Boolean} 是否保存成功
 */
function setLocalData(key, val, partition = 'seemall') {
    let localData = JSON.parse(localStorage.getItem(partition) || '{}');
    if ('object' == typeof key && !Array.isArray(key)) {
        $.extend(localData, key);
    } else if ('string' == typeof key) {
        localData[key] = val;
    } else {
        return false;
    }
    localStorage.setItem(partition, JSON.stringify(localData));
    return true;
};


/**
 * @description: 根据key值和partition 获取本地缓存
 * @param {string} partition 获取哪个存储区域下的缓存,默认是seemall存储区域
 * @param {string} key 获取partition存储区域下 key 对应的值
 * @return: {*} 返回存储的任意类型的值
 */
function getLocalData(key, partition = 'seemall') {
    let localData = JSON.parse(localStorage.getItem(partition) || '{}');
    return localData[key];
};
/**
 * @description: 判断浏览器类型
 */
function myBrowser() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (userAgent.indexOf("Edge") > -1) {
        return "Edge"
    }
    if (isOpera) {
        return "Opera"
    }; //判断是否Opera浏览器
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    } //判断是否Firefox浏览器
    if (userAgent.indexOf("Chrome") > -1) {
        return "Chrome";
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    } //判断是否Safari浏览器
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return "IE";
    }; //判断是否IE浏览器
}


/**
 * @description: 节流函数封装
 * @param {Function} fn 事件处理函数 
 * @param {time} delay 延迟多少时间执行处理函数
 * @param {time} mustRunDelay 必然触发执行的时间间隔
 * @return: 
 */
var throttle = function (fn, delay, mustRunDelay) {
    var timer = null;
    var t_start;
    return function () {
        var context = this,
            args = arguments,
            t_curr = +new Date();
        clearTimeout(timer);
        if (!t_start) {
            t_start = t_curr;
        }
        if (t_curr - t_start >= mustRunDelay) {
            fn.apply(context, args);
            t_start = t_curr;
        } else {
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        }
    };
};

/**
 * @description: 根据name获取地址栏里面的query参数值
 * @param : {String} name
 * @return: 
 */
var getUrlKey = function (name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}


function loadJs(config) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.id = config.id;
    if (!config.id) {
        script.id = "qidian" + parseInt(Math.random() * (999999 - 100000) + 100000, 10);
    }

    script.setAttribute("charset", "utf-8");

    if (config.async) {
        script.setAttribute("async", "async");
        script.setAttribute("defer", "defer");
    }

    if (script.readyState) { // ie游览器
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                config.callback && config.callback();
            }
        }
    } else { //其他
        script.onload = function () {
            config.callback && config.callback();
        }
    };
    if (config.url) {
        script.src = config.url;
        document.getElementsByTagName("body")[0].appendChild(script);
    }

}

/**
 * @description: 复制内容到剪切板
 * @param : {String} cont  需要复制的内容
 * @return: {Boolen}
 */
function copyToClipboard(cont, callback) {
    var oInput = document.createElement('input');
    oInput.value = cont;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    oInput.className = 'oInput';
    oInput.style.position = 'fixed';
    oInput.style.top = '0';
    oInput.style.left = '0';
    oInput.style.width = '1px';
    oInput.style.height = '1px';
    oInput.style.padding = '0';
    oInput.style.border = 'none';
    oInput.style.outline = 'none';
    oInput.style.boxShadow = 'none';
    oInput.style.background = 'transparent';
    try {
        var successful = document.execCommand('copy');
        var msg = successful ? '链接复制成功，您现在可以去粘贴分享' : '该浏览器不支持点击复制到剪贴板';
        callback(msg);
    } catch (err) {
        callback('该浏览器不支持点击复制到剪贴板');
    }

    document.body.removeChild(oInput);
}


//文档的总高度
function getScrollHeight() {
    var scrollHeight = 0,
        bodyScrollHeight = 0,
        documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight =
        bodyScrollHeight - documentScrollHeight > 0
            ? bodyScrollHeight
            : documentScrollHeight;
    return scrollHeight;
}
//浏览器视口的高度
function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}
//滚动的高度
function getScrollTop() {
    var scrollTop = 0,
        bodyScrollTop = 0,
        documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop =
        bodyScrollTop - documentScrollTop > 0
            ? bodyScrollTop
            : documentScrollTop;
    return scrollTop;
}


// 时间戳格式化成字符串时间
function dateFormat(date, format) {
    date = new Date(date);
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        }
        else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
};

//将base64转换为文件对象
function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length; 
    var u8arr = new Uint8Array(n);    // Uint8Array 不支持ie8、ie9
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    //转换成file对象
    return new File([u8arr], filename, {type:mime});
    //转换成成blob对象
    //return new Blob([u8arr],{type:mime});
}

function getOffset(Node, offset) {
    if (!offset) {
        offset = {};
        offset.top = 0;
        offset.left = 0;
    }

    if (Node == document.body) {//当该节点为body节点时，结束递归
        return offset;
    }
    offset.top += Node.offsetTop;

    offset.left += Node.offsetLeft;

    return getOffset(Node.parentNode, offset);//向上累加offset里的值
}

function openWin(url, name, iTop, iLeft) {
    var iWidth = window.screen.availWidth- 10 - iLeft * 2;
    var iHeight = window.screen.availHeight - 60 - iTop * 2;
    return window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ', width = ' + iWidth + ', innerWidth = ' + iWidth + ', top = ' + iTop + ', left = ' + iLeft + ', status = no, toolbar = no, menubar = no, location = no, resizable = no, scrollbars = 0, titlebar = no');
}

// 深拷贝
function deepCopy(obj, cache) {
    if (!cache) cache = []
  
    // just return if obj is immutable value
    if (obj === null || typeof obj !== 'object') {
      return obj
    } else {
        // 特殊处理正则和日期对象
        const Constructor = obj.constructor
        if (Constructor === RegExp) {
            return new Constructor(obj)
        } else if (Constructor === Date) {
            return new Constructor(obj.getTime())
        }
    }
    // if obj is hit, it is in circular structure
    var hit = cache.filter(c => c.original === obj)[0];
    if (hit) {
      return hit.copy
    }
  
    var copy = Array.isArray(obj) ? [] : {}
    // put the copy into cache at first
    // because we want to refer it in recursive deepCopy
    cache.push({
      original: obj,
      copy: copy
    })
  
    Object.keys(obj).forEach(function(key) {
      copy[key] = deepCopy(obj[key], cache)
    })
    return copy
  }

let totalPageSizes=[5, 10, 20, 30, 40, 50];

let totalPageSize=20;
export {
    setLocalData,
    getLocalData,
    myBrowser,
    throttle,
    getUrlKey,
    totalPageSizes,
    totalPageSize,
    loadJs,
    copyToClipboard,
    getScrollHeight,
    getWindowHeight,
    getScrollTop,
    dateFormat,
    dataURLtoFile,
    getOffset,
    openWin,
    deepCopy
}